<template>
  <div class="exam-plan">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <!-- 建议体检时间 -->
      <el-form-item label="体检时间" prop="recommendedDate">
        <el-date-picker
          v-model="formData.recommendedDate"
          type="date"
          placeholder="选择建议体检时间"
          style="width: 100%"
          value-format="x"
        />
      </el-form-item>

      <!-- 体检项目选择 -->
      <el-form-item label="体检项目" prop="itemList">
        <!-- 体检分类选择 -->
        <div v-if="!isViewMode" class="category-selection">
          <el-select
            v-model="selectedCategory"
            placeholder="请选择体检分类"
            style="width: 200px; margin-bottom: 16px"
            @change="handleCategoryChange"
          >
            <el-option
              v-for="category in indicatorLibraryList"
              :key="category.categoryId || category.categoryName"
              :label="category.categoryName"
              :value="category.categoryId || category.categoryName"
            />
          </el-select>
        </div>
        <!-- 体检项目列表 -->
        <el-table :data="examItems" border style="width: 100%">
          <el-table-column width="50">
            <template #header>
              <el-checkbox
                v-model="selectAll"
                :disabled="isViewMode"
                @change="handleSelectAll"
              />
            </template>
            <template #default="{ row }">
              <el-checkbox
                v-model="row.selected"
                :disabled="isViewMode"
                @change="handleItemSelect"
              />
            </template>
          </el-table-column>
          <el-table-column label="体检分类" width="120">
            <template #default="{ row }">
              <span>{{ row.categoryName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="体检项目" width="150">
            <template #default="{ row }">
              <span>{{ row.itemName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="指标详情">
            <template #default="{ row }">
              <div class="indicators-cell">
                <div v-for="(indicator, index) in row.indicators" :key="index">
                  <el-tag size="small" type="info" style="margin: 2px">
                    {{ indicator }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <!-- 提示信息 -->
    <div class="info-tip">
      <el-alert title="体检项目说明" type="info" :closable="false" show-icon>
        <template #default>
          <p>请先选择体检分类，然后从预定义的体检项目中选择需要的项目。</p>
          <p>系统将根据您的选择自动生成体检计划。</p>
        </template>
      </el-alert>
    </div>
  </div>
</template>

<script setup lang="ts">
import type {
  HealthPlanCreateFrom,
  HealthPlanUpdateFrom,
  IndicatorLibraryDTO
} from "@/api/follow";
import { followApi } from "@/api/follow";
import { userKey } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";
import { ElMessage } from "element-plus";
import {
  computed,
  defineEmits,
  defineProps,
  nextTick,
  onMounted,
  ref,
  watch
} from "vue";

const props = defineProps<{
  userId: number;
  planId?: string | string[];
  mode?: "create" | "edit" | "view"; // 组件模式：创建、编辑、查看
}>();

// 默认模式为创建
const defaultMode = computed(() => props.mode || "create");

// 计算是否为查看模式
const isViewMode = computed(() => defaultMode.value === "view");

// 计算是否为编辑模式
const isEditMode = computed(() => defaultMode.value === "edit");

// 计算是否为创建模式
const isCreateMode = computed(() => defaultMode.value === "create");

const emit = defineEmits(["update:modelValue", "submit"]);

// 表单引用
const formRef = ref();

// 全选状态
const selectAll = ref(false);

// 选中的体检分类
const selectedCategory = ref<string | number>("");

const currentInfo = ref<any>({});

onMounted(() => {
  getFollowUpPlanCondition();
});
const indicatorLibraryList = ref<any[]>([]);
const getFollowUpPlanCondition = async () => {
  const response = await followApi.getFollowUpPlanCondition({
    userId: (storageLocal().getItem(userKey) as any).userId
  });
  if (response?.data) {
    indicatorLibraryList.value = response.data.indicatorLibraryList;
    loadExamItemsByCategory();
  }
};

// 体检项目列表
const examItems = ref<
  Array<{
    id: number;
    categoryId?: number;
    categoryName: string;
    itemName: string;
    indicators: string[];
    selected: boolean;
  }>
>([]);

// 表单数据
const formData = ref<HealthPlanCreateFrom>({
  userId: props.userId,
  recommendedDate: "",
  itemList: []
});

// 计算选中的项目
const selectedItems = computed(() => {
  return examItems.value
    .filter(item => item.selected)
    .map(item => ({
      id: item.id,
      categoryId: item.categoryId,
      categoryName: item.categoryName,
      itemName: item.itemName,
      indicators: item.indicators
    }));
});

// 表单验证规则
const rules = {
  recommendedDate: [
    { required: true, message: "请选择建议体检时间", trigger: "change" }
  ],
  itemList: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (selectedItems.value.length === 0) {
          callback(new Error("请至少选择一个体检项目"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
};

// 处理全选
const handleSelectAll = (val: boolean) => {
  examItems.value.forEach(item => {
    item.selected = val;
  });
  updateFormData();
};

// 处理分类变化
const handleCategoryChange = () => {
  console.log("体检分类变化 - 选中的分类:", selectedCategory.value);
  loadExamItemsByCategory();
};

// 根据分类加载体检项目
const loadExamItemsByCategory = () => {
  if (!selectedCategory.value) {
    examItems.value = [];
    return;
  }

  const selectedCategoryData = indicatorLibraryList.value.find(category =>
    [category.categoryId, category.categoryName].includes(
      selectedCategory.value
    )
  );

  if (selectedCategoryData) {
    console.log("[examPlan] 加载体检项目 - 选中的分类数据:", currentInfo.value);

    // 将分类下的所有项目转换为体检项目列表
    examItems.value = selectedCategoryData.itemName.map((itemName, index) => ({
      id: index + 1,
      categoryId: selectedCategoryData.categoryId,
      categoryName: selectedCategoryData.categoryName,
      itemName: itemName,
      indicators: [itemName], // 这里可以根据实际需求调整指标内容
      selected:
        props.mode === "create"
          ? false
          : currentInfo.value.itemList.some(
              (item: IndicatorLibraryDTO) =>
                item.categoryName === selectedCategoryData.categoryName &&
                item.itemName.includes(itemName)
            )
    }));

    console.log("加载体检项目 - 生成的体检项目列表:", examItems.value);
  }
  console.log(
    "[examPlan] examItems.value",
    selectedCategory.value,
    examItems.value,
    selectedItems.value
  );

  updateFormData();

  formRef.value.validate();
};

// 处理单个项目选择
const handleItemSelect = () => {
  selectAll.value = examItems.value.every(item => item.selected);
  updateFormData();
};

// 更新表单数据
const updateFormData = () => {
  // 将选中的体检项目转换为 IndicatorLibraryDTO 格式
  const groupedItems = selectedItems.value.reduce((acc, item) => {
    const existingCategory = acc.find(
      group => group.categoryName === item.categoryName
    );

    if (existingCategory) {
      existingCategory.itemName.push(item.itemName);
    } else {
      acc.push({
        categoryId: item.categoryId,
        categoryName: item.categoryName,
        itemName: [item.itemName]
      });
    }

    return acc;
  }, [] as IndicatorLibraryDTO[]);

  formData.value.itemList = groupedItems;

  console.log("更新表单数据 - 选中的项目:", selectedItems.value);
  console.log("更新表单数据 - 分组后的项目:", groupedItems);
  console.log("更新表单数据 - 表单数据:", formData.value);
};

// 获取体检计划详情
const getExamPlanInfo = async () => {
  if (!props.planId) return;

  try {
    console.log("获取体检计划详情 - 开始获取计划ID:", props.planId);

    const response = await followApi.getFollowUpPlanTaskInfo({
      planId: props.planId
    });

    if (response?.data) {
      const data = response.data;
      console.log("[examPlan] 获取体检计划详情 - 数据获取成功", data);
      currentInfo.value = data;

      formData.value = {
        ...formData.value,
        ...data,
        recommendedDate: String(data.recommendedDate)
      };

      // 如果有体检项目数据，设置分类和项目
      if (data.itemList && data.itemList.length > 0) {
        const firstItem = data.itemList[0];
        selectedCategory.value =
          firstItem.categoryName || firstItem.categoryId || "";

        console.log("[examPlan] firstItem", firstItem, selectedCategory.value);
        // 加载体检项目
        loadExamItemsByCategory();

        // 更新选中状态
        examItems.value.forEach(item => {
          item.selected = data.itemList.some(
            (selected: IndicatorLibraryDTO) =>
              selected.categoryName === item.categoryName &&
              selected.itemName.includes(item.itemName)
          );
        });
        selectAll.value = examItems.value.every(item => item.selected);
      }
    }
  } catch (error) {
    console.error("获取体检计划详情失败:", error);
    ElMessage.error("获取体检计划详情失败");
  }
};

// 提交表单
const submitForm = async () => {
  console.log("提交体检计划表单 - 开始验证和提交，模式:", defaultMode.value);

  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    updateFormData(); // 确保数据最新

    let response;
    if (isCreateMode.value) {
      // 创建新的体检计划
      console.log("体检计划 - 创建模式，调用创建接口");
      response = await followApi.getFollowUpPlanHealthPlanCreate(
        formData.value
      );
    } else if (isEditMode.value && props.planId) {
      // 编辑现有体检计划
      console.log("体检计划 - 编辑模式，调用更新接口，计划ID:", props.planId);
      const updateData: HealthPlanUpdateFrom = {
        ...formData.value,
        planId: props.planId
      };
      response = await followApi.getFollowUpPlanHealthPlanUpdate(updateData);
    } else {
      console.error("体检计划 - 无效的操作模式或缺少计划ID");
      ElMessage.error("操作失败，请检查参数");
      return;
    }

    if (response?.data) {
      console.log("提交体检计划表单 - 提交成功", response.data);
      ElMessage.success(isCreateMode.value ? "创建成功" : "更新成功");
      emit("submit", formData.value);
    }
  } catch (error) {
    console.error("保存体检计划失败:", error);
    ElMessage.error("保存失败，请检查表单内容");
  }
};

// 暴露方法给父组件
defineExpose({
  submitForm
});

// 初始化
onMounted(() => {
  if (props.planId && !isCreateMode.value) {
    getExamPlanInfo();
  }
  updateFormData();
});
</script>

<style lang="scss" scoped>
.exam-plan {
  padding: 20px 0;
  :deep(.el-form-item__label) {
    font-weight: normal;
    color: #606266;
  }

  :deep(.el-table) {
    .el-table__header {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
      }
    }

    .el-checkbox {
      margin-right: 0;
    }
  }

  .indicators-cell {
    line-height: 1.5;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
    white-space: pre-wrap;
  }

  .info-tip {
    margin-top: 16px;

    :deep(.el-alert__content) {
      p {
        margin: 4px 0;
        line-height: 1.5;
      }
    }
  }
}
</style>
